package com.tensquare.user.controller;

import com.tensquare.user.pojo.Admin;
import com.tensquare.user.service.AdminService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

@RestController
@RequestMapping("admin")
public class AdminController {

    @Autowired
    private AdminService adminService;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private HttpServletRequest request;

    //1.添加管理员
    @PostMapping
    public Result addAdmin(@RequestBody Admin admin){
        //1.1调用服务添加
        adminService.add(admin);
        //1.2返回结果
        return new Result(true,StatusCode.OK,"添加管理员成功！");
    }

    //2.管理员登录
    @PostMapping("login")
    public Result login(@RequestBody Admin admin){
        //2.1调用服务判断验证用户
        Admin findAdmin=adminService.login(admin);
        //2.2判断用户是否用过验证，通过则不为空
        if(findAdmin!=null){
            //2.2.1根据
            String token = jwtUtil.getToken(findAdmin.getId(), findAdmin.getLoginname(), "admin");
            //2.2.2
            HashMap hashMap = new HashMap();
            hashMap.put("token",token);
            hashMap.put("name",findAdmin.getLoginname());
            return new Result(true,StatusCode.OK,"登录成功！",hashMap);
        }
        //2.3为空则不通过
        return new Result(false,StatusCode.ERROR,"登录失败！");
    }

    //3.删除管理员
    @DeleteMapping("{adminId}")
    public Result delete(@PathVariable String adminId){
        //3.1从请求作用域中获取claims
        Claims claims = (Claims) request.getAttribute("claims");
        //3.2判断claims是否存在
        if(claims!=null){
            String roles= (String) claims.get("roles");
            //3.2.1判断是否有权限
            if(roles.equals("admin")){
                adminService.delete(adminId);
                return new Result(true,StatusCode.OK,"删除管理员成功！");
            }
        }
        return new Result(false,StatusCode.ERROR,"删除管理员失败!");
    }

}
